from tornado.httpclient import AsyncHTTPClient
import tornado.web
import tornado.ioloop
import tornado.httpclient
from . import utils
import json

'''
#1.3同步提取声纹串
    http://ip:port/receive/syncGetModelStr
    {
        "fileUrl":""
    }
    resp:
    {
        "state":{
            "ok":1,
            "failed":""
        },
        "result":""
    }
'''
class receive_syncGetModelStr(tornado.web.RequestHandler):

    async def post(self, *args, **kwargs):
        resp = None
        try:
            data=json.loads(self.request.body)
            print(data)
            paramerror = utils.checkParam(data,{
                                                    "fileUrl":""
                                                })
            if paramerror == '': #ok
                mediaurls = data['fileUrl'].split(',')
                for url in mediaurls:
                    http_client = AsyncHTTPClient()
                    response = await http_client.fetch(url)
                    print(response)
                    utils.write2file("receive_model.raw", response.body)
                    http_client.close()

                resp = {
                    "state":{
                        "ok":1,
                        "failed": ""
                    },
                    "result":utils.getfakeModelStr()
                }
            else: #failed
                resp = {
                    "state":{
                        "ok":0,
                        "failed": paramerror
                    },
                    "result":""
                }

        except BaseException as e:
            resp = {
                "state":{
                    "ok":0,
                    "failed": str(e)
                },
                "result":""
            }

        self.write(resp)
